package com.hly.tool.csrf;

import com.hly.tool.http.http;
import com.matrixone.apps.framework.ui.UIUtil;
import com.matrixone.jdl.MatrixSession;
import matrix.db.Context;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ：Jack Hao
 * @date ：Created in 2021/9/1 15:55
 * @description：
 */
public class CSRFUtil
{

    /**
     * 获取 登录后的token
     *
     * @param context
     * @return
     */
    public static String getENOCSRFTOKEN(Context context, String loginhost) throws Exception
    {
        String result = "";
        MatrixSession session = context.getSession();
        String sessionId = session.getSessionId();
        String role = session.getRole();
        Map herderMap = new HashMap();
        herderMap.put("Cookie", "JSESSIONID=" + sessionId);
        herderMap.put("SecurityContext", role);
        String tokenResult = http.doGet(loginhost + "/resources/v1/application/CSRF", new BasicHttpParams(), herderMap);
        if (UIUtil.isNullOrEmpty(tokenResult))
        {
            result = "";
        } else
        {
            JSONObject json = new JSONObject(tokenResult);
            String statusCode = json.getString("statusCode");
            if (statusCode.equals("200"))
            {
                JSONObject csrfJson = json.getJSONObject("csrf");
                result = csrfJson.getString("value");
            }
        }
        return result;
    }
}
